package cn.zifangsky.linkedlist.questions;

import org.junit.Test;

import cn.zifangsky.linkedlist.SinglyNode;
import cn.zifangsky.linkedlist.SinglyNodeOperations;

/**
 * 如何从表尾开始输出链表？
 * @author zifangsky
 *
 */
public class Problem_008_ReversePrintList {
	
	/**
	 * 思路：递归，从链表末尾开始输出
	 * @时间复杂度 O(n)
	 * @param headNode
	 * @return
	 */
	public void printFromEnd(SinglyNode headNode){
		if(headNode != null){
			if(headNode.getNext() != null){
				printFromEnd(headNode.getNext());
			}
			
			System.out.print(headNode.getData() + " ");
		}
	}
	
	@Test
	public void testMethods(){
		SinglyNode headNode = new SinglyNode(11);
		
		SinglyNode currentNode = headNode;
		for(int i=2;i<=5;i++){
			SinglyNode tmpNode = new SinglyNode(11 * i);
			currentNode.setNext(tmpNode);
			currentNode = tmpNode;
		}
		
		//遍历初始链表
		SinglyNodeOperations.print(headNode);
				
		//从末尾开始遍历链表
		printFromEnd(headNode);
	}
	
}
